package openhaven.control.message;

import openhaven.StringUtil;
import openhaven.control.net.Message;
import openhaven.model.Coord;

import org.apache.log4j.Logger;

public abstract class RichMessage
{
    // public abstract void notifyListeners(Map<Object, Object> listeners);

    private static final Logger LOG = Logger.getLogger(RichMessage.class);

    String string(final Object[] args2)
    {
        final StringBuffer buf = new StringBuffer("[");
        for (final Object object : args2)
        {
            buf.append(object);
            buf.append(", ");
        }
        buf.append("]");
        return buf.toString();
    }

    public static RichMessage process(final Message message)
    {
        switch (message.type)
        {
            case Message.RMSG_NEWWDG:
                return new NewWidgetMessage(message);
            case Message.RMSG_WDGMSG:
                return new WidgetMessage(message);
            case Message.RMSG_DSTWDG:
                return new DestroyWidgetMessage(message);
        }
        return message;
    }

    public static class NewWidgetMessage extends RichMessage
    {
        final public int id;
        final public String type;
        final public Coord c;
        final public int parent;
        final public Object[] args;

        public NewWidgetMessage(final Message msg)
        {
            id = msg.uint16();
            type = msg.string();
            c = msg.coord();
            parent = msg.uint16();
            args = msg.list();
        }

        @Override
        public String toString()
        {
            return StringUtil.tokenSeparated(" ", "NewWidgetMessage", id + "", type, c.toString(), parent + "", string(args));
        }

    }

    public static class WidgetMessage extends RichMessage
    {
        public final int id;
        public final String name;
        final public Object[] args;

        public WidgetMessage(final Message msg)
        {
            id = msg.uint16();
            name = msg.string();
            args = msg.list();
        }

        @Override
        public String toString()
        {
            return StringUtil.tokenSeparated(" ", "WidgetMessage", id + "", name, string(args));
        }
    }

    public static class DestroyWidgetMessage extends RichMessage
    {
        public final int id;

        public DestroyWidgetMessage(final Message msg)
        {
            id = msg.uint16();
        }

        @Override
        public String toString()
        {
            return StringUtil.tokenSeparated(" ", "DestroyWidgetMessage", id + "");
        }
    }
}
